<?php
/**
 * Created by IntelliJ IDEA.
 * User: admin
 * Date: 5/8 0008
 * Time: 16:28
 */

namespace app\api\controller;

use think\Controller;
use think\Db;

class Torder extends Controller
{
    protected $tlinxsdk;

    public function __construct()
    {
        parent::__construct();
        $this->tlinxsdk = new \tlinxsdk();
    }

    //商户列表
    public function merlist()
    {
        $data = null;
        $data['page'] = '1';
        $result =  $this->tlinxsdk->API('merchant', $data);
        print_r($result);
    }


    //回掉新增订单接口
    public  function notify()
    {
        $map = request()->get();
        $tlinxsdk = $this->tlinxsdk;
        $res = model("Torder")->where(['ord_no' => input('out_no')])->find();
        if ($res) {
            //查询订单详情
            $data['ord_no'] = $map['ord_no'];  //订单号
            //$data['ord_no'] ='91487650846891319854';
            $result = $tlinxsdk->API('order', $data);
            $map = $result['data']['list'][0];
            $map['ord_status'] = input('status');
            $map['ttg_no'] = $map['ord_no'];//2017年2月16日10:58:17  新增淘淘谷平台交易单号字段
            $map['ord_no'] = input('out_no');
            if(!input('ord_type')){
                if($res['ord_type']!=2){
                    //$map['ord_type']='1';//2017年2月20日15:41:08 暂时没有接受到消息类型
                }
            }else{
                if($res['ord_type'] != 2){//为退款时，不更改消费状态
                    $map['ord_type']=input('ord_type');
                }
            }
            $map['ord_add_time'] = strtotime($map['ord_add_time']);//2017年2月20日15:06:08  这里的时间有问题
            $model  = model("Torder");
            $saveres=$model->isUpdate(true,['ord_no' => input('out_no')])->save($map);
        } else {
            echo 'error';
        }
    }

    #####################################################################################
    //回掉新增订单接口(新版) 2017年5月22日 15:51:56
    public  function notifynew()
    {
        $map = request()->get();
        //获取淘淘谷门店的具体信息
        if(!request()->param("ttgid")){
            die("error");
        }
        $ttginfo=Db::name("ttg")->where("id",request()->param("ttgid"))->find();
        if(empty($ttginfo["ttgid"])||empty($ttginfo["ttgkey"])){
            die("淘淘谷配置错误!");
        }
        $tlinxsdk=new \Mylinx($ttginfo["ttgid"], $ttginfo["ttgkey"],request()->param("ttgid"));
        $res = model("Torder")->where(['ord_no' => input('out_no')])->find();
        if ($res) {
            //查询订单详情
            $data['ord_no'] = $map['ord_no'];  //订单号
            //$data['ord_no'] ='91487650846891319854';
            $result = $tlinxsdk->API('order', $data);
            $map = $result['data']['list'][0];
            $map['ord_status'] = input('status');
            $map['ttg_no'] = $map['ord_no'];//2017年2月16日10:58:17  新增淘淘谷平台交易单号字段
            $map['ord_no'] = input('out_no');
            if(!input('ord_type')){
                if($res['ord_type']!=2){
                    //$map['ord_type']='1';//2017年2月20日15:41:08 暂时没有接受到消息类型
                }
            }else{
                if($res['ord_type'] != 2){//为退款时，不更改消费状态
                    $map['ord_type']=input('ord_type');
                }
            }
            $map['ord_add_time'] = strtotime($map['ord_add_time']);//2017年2月20日15:06:08  这里的时间有问题
            $model  = model("Torder");
            $saveres=$model->isUpdate(true,['ord_no' => input('out_no')])->save($map);
        } else {
            die('error');
        }
    }

    public function text(){
        $data['ord_no'] ='91487660700774225216';
        $tlinxsdk = $this->tlinxsdk;
        $result = $tlinxsdk->API('order', $data);
        dump($result);
    }

    //  取消订单回掉接口
    public  function orderRefund()
    {
        $map = input('get.');
        $tlinxsdk = $this->tlinxsdk;
        $res = model("Torder")->where(['ord_no' => input('out_no')])->find();
        if ($res) {
            //查询订单详情
            $data['ord_no'] = input('ord_no');  //测试订单号
            // $data['ord_no'] ='91486726539225150225';
            $result = $tlinxsdk->API('order', $data);
            $map = $result['data']['list'][0];
            $map['ord_status'] = input('status');
            $map['ord_no'] = input('out_no');
            $model  = model("Torder");
            $model->where(['ord_no' => input('out_no')])->save($map);
            $res = $model->getLastSql();
        } else {
            echo 'error';
        }
    }


    //本地订单
    public function order()
    {
        if (IS_POST) {
            $res = model('token')->ku();
            $tid = model('custom')->getid($res);  //2017-02-11 16:31:51
            if ($res['status'] === 1) {
                return json($res);
            } else {
                $res = model('Torder')->addOrder($tid['taostorenum']);
                //$tlinxsdk = $this->tlinxsdk;
                $data['xcs_no'] = $tid['taostorenum'];  //小菜神的门店id
                // $result = $tlinxsdk->API('shop/openid', $data);
                $res['appinfo'] = ['open_id' => $tid['openid'], 'open_key' => $tid['openkey'],'customname'=>$tid['customname'],'taostorenum'=>$tid['taostorenum'],'customid'=>str_pad($tid['id'],6,0,STR_PAD_LEFT)];
                return json($res);
            }
        } else {
            echo '非法访问';
        }

    }


    /**
     * POS新版生成订单2017年5月22日 16:06:00
     * @return \think\response\Json
     */
    public function nativeorder()
    {
        $input =file_get_contents('php://input');
        //将$input decode成数组
        parse_str($input,$myArray);
        //$myArray=$_POST;
        $userid=Index::verifytoken($myArray["token"]);
        if(!$userid){
            return json(["status"=>0,"msg"=>"需要重新登录"]);
        }
        $shopinfo=model("manager")->where("y_manager.id",$userid)->join("y_shop","y_shop.id=y_manager.shopid","left")->find();
        if (!$shopinfo) {
            return json(["status"=>0,"msg"=>"无门店"]);
        } else {
            if(!$shopinfo['ttgid']){
                return json(["status"=>0,"msg"=>"淘淘谷配置错误"]);
            }
            $res = model('Torder')->addOrder($userid);
            $res["fee"]=round($myArray["ord_trade_amount"]);
            $data['xcs_no'] = $shopinfo['ttgshopno'];  //小菜神的门店id
            $res['appinfo'] = [
                'open_id' => $shopinfo['openid'],
                'open_key' => $shopinfo['openkey'],
                'notifyurl'=>"http://xtshop.xwdcook.com/index.php/api/Torder/notifynew/ttgid/{$shopinfo['ttgid']}",
                'customname'=>$shopinfo['nickname'],
                'taostorenum'=>$shopinfo['ttgshopno'],
                'customid'=>str_pad($userid,6,0,STR_PAD_LEFT)
            ];
            return json($res);
        }
    }

    //订单取消
    public function refund()
    {
        $userid=Index::verifytoken(request()->post("token"));
        if(!$userid){
            return json(["status"=>0,"msg"=>"需要重新登录"]);
        }
        $shopinfo=model("manager")->where("y_manager.id",$userid)->join("y_shop","y_shop.id=y_manager.shopid","left")->find();
        if (!$shopinfo){
            return json(["status"=>0,"msg"=>"无门店"]);
        } else {
            $tlinxsdk = $this->tlinxsdk;
            $data['ord_type'] = '2';
            $data['ord_no'] = input('ord_no');

            $data1['shop_no'] = $shopinfo['ttgshopno'];
            $res = model('Torder')->getRefund();
            if ($res['status'] === 0) {
                return json($res);
            } else {
                $info = [];
                //$result=$tlinxsdk->API('order',$data);
                $result = $tlinxsdk->API('shop/openid', $data1);
                $info['status'] = 1;
                $info['ord_no'] = input('ord_no');
                $info['refund_no'] = $res;
                $info['appinfo'] = ['open_id' => $result['data']['open_id'], 'open_key' => $result['data']['open_key']];
                return json($info);
            }
        }
    }

    /**
     * 新版订单取消2017年5月22日 16:23:53
     * @return \think\response\Json
     */
    public function refundnew()
    {
        $userid=Index::verifytoken(request()->post("token"));
        if(!$userid){
            return json(["status"=>0,"msg"=>"需要重新登录"]);
        }
        $shopinfo=model("manager")->where("y_manager.id",$userid)->join("y_shop","y_shop.id=y_manager.shopid","left")->find();
        if (!$shopinfo){
            return json(["status"=>0,"msg"=>"无门店"]);
        } else {
            if(empty($shopinfo["openid"])||empty($shopinfo["openkey"])){
                return json(["status"=>0,"msg"=>"淘淘谷门店配置有误"]);
            }
            $data['ord_type'] = '2';
            $data['ord_no'] = input('ord_no');
            $data1['shop_no'] = $shopinfo['ttgshopno'];
            $res = model('Torder')->getRefund();
            if ($res['status'] === 0) {
                return json($res);
            } else {
                $info = [];
                //$result=$tlinxsdk->API('order',$data);
                $info['status'] = 1;
                $info['ord_no'] = input('ord_no');
                $info['refund_no'] = $res;
                $info['appinfo'] = [
                    'open_id' => $shopinfo["openid"],
                    'open_key' => $shopinfo["openkey"]
                ];
                return json($info);
            }
        }
    }


    //訂單詳情(淘淘谷接口查询)
    public function orderDetail(){
        $res = model('token')->ku();
        if ($res['status'] === 1) {
            return json($res);
        } else {
            $tlinxsdk = $this->tlinxsdk;
            $data['ord_no'] = '91485142005961649199';  //测试订单号
            $result = $tlinxsdk->API('order', $data);
            $info = ['status'=>$result['data']['list']['0']['ord_status'],'typename'=>$result['data']['list']['0']['ord_name'],'ordersn'=>$data['ord_no'],'storename'=>$result['data']['list']['0']['shop_name'],'createtime'=>$result['data']['list']['0']['ord_trade_pay_time'],
                'discountfee'=>$result['data']['list']['0']['ord_discount_amount'],
                'realfee'=>$result['data']['list']['0']['ord_trade_amount'],
                'servicefee'=>$result['data']['list']['0']['ord_fee'],
            ];
            return json($info);
        }

    }

    //收银订单记录  2017-02-11 17:21:34 √
    public  function orderRecord(){
        if(request()->post()){
            $userid=Index::verifytoken(request()->post("token"));
            if(!$userid){
                return json(["status"=>0,"msg"=>"需要重新登录"]);
            }
            $shopinfo=model("manager")->where("y_manager.id",$userid)->join("y_shop","y_shop.id=y_manager.shopid","left")->find();
            if (!$shopinfo) {
                return json(["status"=>0,"msg"=>"无门店"]);
            } else {
                $list = model('Torder')->getRecord($shopinfo['ttgshopno']);
                return json($list);
            }
        }else{
            echo '非法访问';
        }

    }


    //小菜神账单详情(本地数据库查询)
    public function orderLocalDetail(){
        if(request()->post()){
            $userid=Index::verifytoken(request()->post("token"));
            if(!$userid){
                return json(["status"=>0,"msg"=>"需要重新登录"]);
            }
            $shopinfo=model("manager")->where("y_manager.id",$userid)->join("y_shop","y_shop.id=y_manager.shopid","left")->find();
            if (!$shopinfo) {
                return json(["status"=>0,"msg"=>"无门店"]);
            } else {
                $list = model('Torder')->getInfo();
                return json($list);
            }
        }else{
            echo '非法访问';
        }
    }

    //小菜神账单详情(本地数据库查询)2017年3月11日 15:20:34
    public function orderLocalDetailNew(){
        if(request()->post()){
            $res = model('token')->ku();  //获取小菜神门店id
            if ($res['status'] === 1) {
                return json($res);
            } else {
                $list = model('Order')->getInfoNew();
                return json($list);
            }
        }else{
            echo '非法访问';
        }
    }

    //订单统计
    public function orderData(){
        // if(request()->post()){
        $res = model('token')->ku();  //获取小菜神门店id
        if ($res['status'] === 1) {
            return json($res);
        } else {
            $tid = model('custom')->getid($res);
            $list = model('Order')->getData($tid['taostorenum']);
            return json($list);
        }
    }

}